from utils.paths import get_home_dir, get_app_data_dir, get_storage_path, get_db_path, get_machine_id_path,get_workspace_storage_path
from augutils.json_modifier import modify_telemetry_ids
from augutils.sqlite_modifier import clean_augment_data
from augutils.workspace_cleaner import clean_workspace_storage
import os
import urllib.request
import urllib.error

def check_online_status():
    """检查在线状态验证"""
    print("正在验证程序状态...")

    try:
        # 设置请求超时时间为10秒
        url = "https://gitee.com/xnstudent/ffre/raw/master/status.txt"

        # 创建请求对象，设置User-Agent避免被拒绝
        req = urllib.request.Request(url)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36')

        # 发送请求
        with urllib.request.urlopen(req, timeout=10) as response:
            status_content = response.read().decode('utf-8').strip()

        print(f"获取到状态: {status_content}")

        if status_content == "1":
            print("✓ 验证成功，程序可以正常使用！")
            return True
        elif status_content == "2":
            print("✗ 程序当前不可用，请稍后再试。")
            return False
        else:
            print(f"✗ 未知状态码: {status_content}")
            return False

    except urllib.error.URLError as e:
        print(f"✗ 网络连接失败: {e}")
        print("请检查网络连接或稍后重试。")
        return False
    except Exception as e:
        print(f"✗ 验证过程中发生错误: {e}")
        return False

def show_menu():
    """显示主菜单"""
    print("\n" + "="*50)
    print("           Free AugmentCode 工具")
    print("="*50)
    print("1. 查看系统路径信息")
    print("2. 修改 Telemetry IDs")
    print("3. 清理 SQLite 数据库")
    print("4. 清理工作区存储")
    print("5. 执行完整清理（推荐）")
    print("0. 退出程序")
    print("="*50)

def show_system_paths():
    """显示系统路径信息"""
    print("\n系统路径信息:")
    print("-" * 40)
    print(f"用户目录: {get_home_dir()}")
    print(f"应用数据目录: {get_app_data_dir()}")
    print(f"存储文件路径: {get_storage_path()}")
    print(f"数据库路径: {get_db_path()}")
    print(f"机器ID路径: {get_machine_id_path()}")
    print(f"工作区存储路径: {get_workspace_storage_path()}")

    # 检查文件是否存在
    print("\n文件存在状态:")
    print("-" * 40)
    paths = {
        "存储文件": get_storage_path(),
        "数据库文件": get_db_path(),
        "机器ID文件": get_machine_id_path(),
        "工作区目录": get_workspace_storage_path()
    }

    for name, path in paths.items():
        exists = "✓ 存在" if os.path.exists(path) else "✗ 不存在"
        print(f"{name}: {exists}")

def modify_ids():
    """修改 Telemetry IDs"""
    print("\n正在修改 Telemetry IDs...")
    print("-" * 40)
    try:
        result = modify_telemetry_ids()
        print("✓ 修改成功！")
        print(f"\n备份文件:")
        print(f"  存储文件备份: {result['storage_backup_path']}")
        if result['machine_id_backup_path']:
            print(f"  机器ID备份: {result['machine_id_backup_path']}")

        print(f"\n旧 IDs:")
        print(f"  机器ID: {result['old_machine_id']}")
        print(f"  设备ID: {result['old_device_id']}")

        print(f"\n新 IDs:")
        print(f"  机器ID: {result['new_machine_id']}")
        print(f"  设备ID: {result['new_device_id']}")

    except FileNotFoundError as e:
        print(f"✗ 错误: {e}")
    except Exception as e:
        print(f"✗ 发生错误: {e}")

def clean_database():
    """清理 SQLite 数据库"""
    print("\n正在清理 SQLite 数据库...")
    print("-" * 40)
    try:
        db_result = clean_augment_data()
        print("✓ 数据库清理完成！")
        print(f"  数据库备份: {db_result['db_backup_path']}")
        print(f"  删除记录数: {db_result['deleted_rows']}")
    except FileNotFoundError as e:
        print(f"✗ 错误: {e}")
    except Exception as e:
        print(f"✗ 发生错误: {e}")

def clean_workspace():
    """清理工作区存储"""
    print("\n正在清理工作区存储...")
    print("-" * 40)
    try:
        ws_result = clean_workspace_storage()
        print("✓ 工作区清理完成！")
        print(f"  工作区备份: {ws_result['backup_path']}")
        print(f"  删除文件数: {ws_result['deleted_files_count']}")

        if ws_result.get('failed_operations'):
            print(f"  失败操作数: {len(ws_result['failed_operations'])}")
        if ws_result.get('failed_compressions'):
            print(f"  压缩失败数: {len(ws_result['failed_compressions'])}")

    except FileNotFoundError as e:
        print(f"✗ 错误: {e}")
    except Exception as e:
        print(f"✗ 发生错误: {e}")

def full_cleanup():
    """执行完整清理"""
    print("\n开始执行完整清理...")
    print("="*50)

    print("\n⚠️  重要提醒:")
    print("  1. 请确保已完全关闭 VS Code")
    print("  2. 请确保已退出 AugmentCode 插件")
    print("  3. 此操作将修改系统文件，建议先备份")

    confirm = input("\n确认执行完整清理吗？(y/N): ").strip().lower()
    if confirm not in ['y', 'yes', '是']:
        print("操作已取消。")
        return

    print("\n开始清理...")

    # 1. 修改 Telemetry IDs
    print("\n[1/3] 修改 Telemetry IDs")
    modify_ids()

    # 2. 清理数据库
    print("\n[2/3] 清理 SQLite 数据库")
    clean_database()

    # 3. 清理工作区
    print("\n[3/3] 清理工作区存储")
    clean_workspace()

    print("\n" + "="*50)
    print("🎉 完整清理已完成！")
    print("现在可以重新启动 VS Code 并使用新邮箱登录 AugmentCode 插件。")
    print("="*50)

def main():
    """主函数"""
    # 程序启动时进行在线验证
    print("="*50)
    print("           Free AugmentCode 工具")
    print("="*50)

    if not check_online_status():
        print("\n程序验证失败，即将退出...")
        input("按回车键退出...")
        return

    print("\n验证通过，欢迎使用！")
    input("按回车键继续...")

    while True:
        show_menu()
        choice = input("\n请选择操作 (0-5): ").strip()

        if choice == "0":
            print("\n感谢使用 Free AugmentCode 工具！")
            break
        elif choice == "1":
            show_system_paths()
        elif choice == "2":
            modify_ids()
        elif choice == "3":
            clean_database()
        elif choice == "4":
            clean_workspace()
        elif choice == "5":
            full_cleanup()
        else:
            print("\n❌ 无效选择，请输入 0-5 之间的数字。")

        if choice != "0":
            input("\n按回车键继续...")

if __name__ == "__main__":
    main()